package com.kuanter.kuanterauto.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.MessageInfo;

public class DBManager {  
    private DBHelper helper;  
    private SQLiteDatabase db;  
    private int messageCount = 0;
    
      
    public DBManager(Context context) {  
        helper = new DBHelper(context);  
        //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);  
        //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里  
        db = helper.getWritableDatabase();  
        
    }  
      
    /** 
     * add messages 
     * @param messages 
     */  
    public void add(List<MessageInfo> messages) {  
    	db = helper.getWritableDatabase();  
        db.beginTransaction();  //开始事务  
        try {  
            for (MessageInfo message : messages) {  
            	
            	db.execSQL("INSERT INTO message VALUES(null, ?, ?, ?)", new Object[]{ message.title, message.content, message.pushTime});
                messageCount++;
            }  
            db.setTransactionSuccessful();  //设置事务成功完成  
        } finally {  
            db.endTransaction();    //结束事务  
        }  
        if(messageCount > MainConstants.MOSTMESSAGE)
        {
        	deleteOldMessage();
        }
    }  
      
    /** 
     * update message's pushTime 
     * @param message 
     */  
    public void updatePushTime(MessageInfo message) {  
        ContentValues cv = new ContentValues();  
        cv.put("pushTime", message.pushTime);  
        db.update("message", cv, "title = ?", new String[]{message.title});  
    }  
      
    /** 
     * delete old message 
     * @param message 
     */  
    public void deleteOldMessage() {  
		
    	 Cursor c = queryTheCursor(false);  
    	 int count = messageCount - MainConstants.MOSTMESSAGE;
    	 db.beginTransaction();
         while ((c.moveToNext())&&(count>0)) 
         {  
        	  //更新数据  
             db.execSQL("delete from message where title=?",
     				new Object[] { c.getString(c.getColumnIndex("title")) });
             count--;
             messageCount--;
             
         }  
         db.setTransactionSuccessful();
         db.endTransaction();
         c.close(); 
         
    	
        
    }  
    
    /** 
     * delete old message 
     * @param message 
     */  
    public void deleteMessage(String sqlId) {  
		
    	 Cursor c = queryTheCursor(false);  
    	 int count = messageCount - MainConstants.MOSTMESSAGE;
    	 db.beginTransaction();
          
        	  //更新数据  
             db.execSQL("delete from message where _id=?",
     				new Object[] { sqlId });
             count--;
             messageCount--;
         db.setTransactionSuccessful();
         db.endTransaction();
         c.close(); 
    }  
      
    /** 
     * query all messages, return list 
     * @return List<Message> 
     */  
    public List<MessageInfo> query() {  
        ArrayList<MessageInfo> messages = new ArrayList<MessageInfo>();  
        Cursor c = queryTheCursor(true);  
        while (c.moveToNext()) {  
            MessageInfo message = new MessageInfo();   
            message.title = c.getString(c.getColumnIndex("title"));  
            message.pushTime = c.getString(c.getColumnIndex("pushTime"));  
            message.content = c.getString(c.getColumnIndex("content"));  
            message.sqlID = c.getInt(c.getColumnIndex("_id")) + "";
            messages.add(message); 
            messageCount++;
        }  
        c.close();  
        return messages;  
    }  
      
    /** 
     * query all messages, return cursor 
     * @return  Cursor 
     */  
    public Cursor queryTheCursor(Boolean desc) {  
    	Cursor c ;
    	if(desc)
    		c = db.rawQuery("SELECT * FROM message order by _id desc", null);
    	else
    		c = db.rawQuery("SELECT * FROM message order by _id", null);
        return c;  
    }  
      
    /** 
     * close database 
     */  
    public void closeDB() {  
        db.close();  
    }  
}  
